/**
 * 留言管理相关的自定义Hook
 */
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '../services/api';
import { Message, MessageCreate, MessageUpdate, MessageStats, PaginatedResponse } from '../types';

// 查询键常量
const QUERY_KEYS = {
  messages: ['messages'] as const,
  messageStats: ['messages', 'stats'] as const,
};

// 留言API函数
const messageApi = {
  getMessages: async (params: {
    page?: number;
    size?: number;
    keyword?: string;
    is_read?: boolean;
    is_replied?: boolean;
  }): Promise<PaginatedResponse<Message>> => {
    const searchParams = new URLSearchParams();
    if (params.page) searchParams.append('page', params.page.toString());
    if (params.size) searchParams.append('size', params.size.toString());
    if (params.keyword) searchParams.append('keyword', params.keyword);
    if (params.is_read !== undefined) searchParams.append('is_read', params.is_read.toString());
    if (params.is_replied !== undefined) searchParams.append('is_replied', params.is_replied.toString());
    
    return api.get<PaginatedResponse<Message>>(`/api/messages?${searchParams.toString()}`);
  },

  getMessage: async (id: number): Promise<Message> => {
    return api.get<Message>(`/api/messages/${id}`);
  },

  createMessage: async (data: MessageCreate): Promise<Message> => {
    return api.post<Message>('/api/messages', data);
  },

  updateMessage: async (id: number, data: MessageUpdate): Promise<Message> => {
    return api.put<Message>(`/api/messages/${id}`, data);
  },

  deleteMessage: async (id: number): Promise<{ message: string }> => {
    return api.delete<{ message: string }>(`/api/messages/${id}`);
  },

  markMessageRead: async (id: number): Promise<Message> => {
    return api.post<Message>(`/api/messages/${id}/mark-read`);
  },

  markAllMessagesRead: async (): Promise<{ message: string }> => {
    return api.post<{ message: string }>('/api/messages/mark-all-read');
  },

  getMessageStats: async (): Promise<MessageStats> => {
    return api.get<MessageStats>('/api/messages/stats');
  },
};

/**
 * 获取留言列表
 */
export const useMessages = (params: {
  page?: number;
  size?: number;
  keyword?: string;
  is_read?: boolean;
  is_replied?: boolean;
} = {}) => {
  return useQuery({
    queryKey: [...QUERY_KEYS.messages, params],
    queryFn: () => messageApi.getMessages(params),
    staleTime: 30 * 1000, // 30秒内数据被认为是新鲜的
  });
};

/**
 * 获取单个留言详情
 */
export const useMessage = (id: number) => {
  return useQuery({
    queryKey: ['message', id],
    queryFn: () => messageApi.getMessage(id),
    enabled: !!id,
    staleTime: 5 * 60 * 1000, // 5分钟内数据被认为是新鲜的
  });
};

/**
 * 获取留言统计
 */
export const useMessageStats = () => {
  return useQuery({
    queryKey: QUERY_KEYS.messageStats,
    queryFn: () => messageApi.getMessageStats(),
    staleTime: 60 * 1000, // 1分钟内数据被认为是新鲜的
  });
};

/**
 * 创建留言
 */
export const useCreateMessage = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: MessageCreate) => messageApi.createMessage(data),
    onSuccess: () => {
      // 刷新留言列表和统计
      queryClient.invalidateQueries({ 
        queryKey: QUERY_KEYS.messages,
        exact: false 
      });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.messageStats });
    },
  });
};

/**
 * 更新留言
 */
export const useUpdateMessage = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: MessageUpdate }) =>
      messageApi.updateMessage(id, data),
    onSuccess: (updatedMessage) => {
      // 刷新留言列表和统计
      queryClient.invalidateQueries({
        queryKey: QUERY_KEYS.messages,
        exact: false
      });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.messageStats });
      // 更新单个留言缓存
      queryClient.setQueryData(['message', updatedMessage.id], updatedMessage);
    },
  });
};

/**
 * 删除留言
 */
export const useDeleteMessage = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: number) => messageApi.deleteMessage(id),
    onSuccess: () => {
      // 刷新留言列表和统计
      queryClient.invalidateQueries({
        queryKey: QUERY_KEYS.messages,
        exact: false
      });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.messageStats });
    },
  });
};

/**
 * 标记留言为已读
 */
export const useMarkMessageRead = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: number) => messageApi.markMessageRead(id),
    onSuccess: (updatedMessage) => {
      // 刷新留言列表和统计
      queryClient.invalidateQueries({
        queryKey: QUERY_KEYS.messages,
        exact: false
      });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.messageStats });
      // 更新单个留言缓存
      queryClient.setQueryData(['message', updatedMessage.id], updatedMessage);
    },
  });
};

/**
 * 标记所有留言为已读
 */
export const useMarkAllMessagesRead = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: () => messageApi.markAllMessagesRead(),
    onSuccess: () => {
      // 刷新留言列表和统计
      queryClient.invalidateQueries({
        queryKey: QUERY_KEYS.messages,
        exact: false
      });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.messageStats });
    },
  });
};
